#include "DHT11.h"


void delay(uint16_t us)
{
	__HAL_TIM_SET_COUNTER(&htim3, 0);
	while(__HAL_TIM_GET_COUNTER(&htim3) < us)
	{}
}


void dht11_pin_in()
{
	GPIO_InitTypeDef GPIO_InitStruct = {0};
	
	GPIO_InitStruct.Pin = DHT11_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
  HAL_GPIO_Init(DHT11_GPIO_Port, &GPIO_InitStruct);
}
	
	
void dht11_pin_out()
{
	GPIO_InitTypeDef GPIO_InitStruct = {0};
	
	GPIO_InitStruct.Pin = DHT11_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
  HAL_GPIO_Init(DHT11_GPIO_Port, &GPIO_InitStruct);
}

void dht11_read(float* temp, float* humid)
{
	uint8_t data[5] = {0,0,0,0,0};
	
	dht11_pin_out();
	
	DHT11_LOW;
	HAL_Delay(20);
	DHT11_HIGH;
	delay(35);
	
	dht11_pin_in();
	
	delay(5);
	
	if(DHT11_READ == GPIO_PIN_SET) {
		return;
	}
	while(DHT11_READ == GPIO_PIN_RESET) 
	{}
	while(DHT11_READ == GPIO_PIN_SET) 
	{}
	
	for(uint8_t i=0; i<5; ++i) {
	
		for(uint8_t b=0; b<8; ++b) {
				while(DHT11_READ == GPIO_PIN_RESET) 
				{}
					
				__HAL_TIM_SET_COUNTER(&htim3, 0);	
				while(DHT11_READ == GPIO_PIN_SET) 
				{}
				uint16_t value = __HAL_TIM_GET_COUNTER(&htim3);
					
				data[i] <<= 1;
					
				if(value > 50) {
					data[i] |= 0x01;
				}
		}	
	}
	
	delay(60);
	dht11_pin_out();
	DHT11_HIGH;
	
	*humid = data[0] * 1.0f + (data[1] * 0.00392f);
	*temp = data[2] * 1.0f + (data[3] * 0.00392f);
}
